package com.example.checkqufuface.View.QufuKaProject;

import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.hardware.usb.UsbDevice;
import android.hardware.usb.UsbManager;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.example.checkqufuface.Base.BaseActivity;
import com.example.baselibrary.Utils.Customer;
import com.example.baselibrary.Utils.LogUtil;
import com.example.baselibrary.Utils.SPUtils;
import com.example.checkqufuface.Utils.SelfToastUtil;
import com.example.baselibrary.Utils.StringUtil;
import com.example.baselibrary.Utils.TimeUtil;
import com.example.checkqufuface.Customer.BottomDialog;
import com.example.checkqufuface.Customer.CustomChangePwWindow;
import com.example.checkqufuface.Customer.SearKaDialog;
import com.example.checkqufuface.Customer.SettingBindDialog;
import com.example.checkqufuface.R;
import com.example.checkqufuface.RetrufitHelp.BaseSubscriber;
import com.example.checkqufuface.RetrufitHelp.ExceptionHandle;
import com.example.checkqufuface.RetrufitHelp.RetrofitClient;
import com.example.checkqufuface.Server.RefreshTokenService;
import com.example.checkqufuface.View.QufuFaceProject.LoginActivity;
import com.example.checkqufuface.bean.QufuAddOrRelieveTerminalBindRequsetBean;
import com.example.checkqufuface.bean.QufuAddOrRelieveTerminalBindResultBean;
import com.example.checkqufuface.bean.QufuPeopleCardSaleRequsetBean;
import com.example.checkqufuface.bean.QufuPeopleCardSaleResultBean;
import com.example.checkqufuface.bean.QufuUpdateUserPassWordRequsetBean;
import com.example.checkqufuface.bean.QufuUpdateUserPassWordResultBean;
import com.example.checkqufuface.bean.QufufTerminalTypeListRequestBean;
import com.example.checkqufuface.bean.QufufTerminalTypeListResultBean;
import com.zkteco.android.biometric.core.device.ParameterHelper;
import com.zkteco.android.biometric.core.device.TransportType;
import com.zkteco.android.biometric.core.utils.LogHelper;
import com.zkteco.android.biometric.module.idcard.IDCardReader;
import com.zkteco.android.biometric.module.idcard.IDCardReaderExceptionListener;
import com.zkteco.android.biometric.module.idcard.IDCardReaderFactory;
import com.zkteco.android.biometric.module.idcard.exception.IDCardReaderException;
import com.zkteco.android.biometric.module.idcard.meta.IDCardInfo;
import com.zkteco.android.biometric.module.idcard.meta.IDPRPCardInfo;

import java.io.File;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

public class QufuKaHomeActivity extends BaseActivity {

    private RelativeLayout setting;
    private LinearLayout makeKa;
    private LinearLayout searchKa;
    private TextView changePw;
    private QufuUpdateUserPassWordRequsetBean userPassWordRequsetBean;
    private CustomChangePwWindow changePwWindow;
    private BottomDialog dialog;
    private SearKaDialog searDialog;
    private SettingBindDialog bindDialog;

    // 曲阜 中身份证识别 新的集成

    private static final int VID = 1024;    //IDR VID
    private static final int PID = 50010;     //IDR PID
    private IDCardReader idCardReader = null;
    private boolean bopen = false;
    private boolean bStoped = false;
    private int mReadCount = 0;
    private CountDownLatch countdownLatch = null;

    private Context mContext = null;
    private UsbManager musbManager = null;
    private final String ACTION_USB_PERMISSION = "com.example.scarx.idcardreader.USB_PERMISSION";

    private long timeNew;
    private long timeOld;
    private String OldID;

    private boolean isShowMakeKa = false;
    private boolean isShowSearKa = false;


    private QufuAddOrRelieveTerminalBindRequsetBean bindRequsetBean;


    private BroadcastReceiver mUsbReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();

            if (ACTION_USB_PERMISSION.equals(action)) {
                synchronized (this) {
                    UsbDevice device = intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
                    if (intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, false)) {
                        try {
                            OpenDevice();
                        } catch (Exception e) {

                        }
                    } else {
                        Toast.makeText(mContext, "USB未授权", Toast.LENGTH_SHORT).show();
                        //mTxtReport.setText("USB未授权");
                    }
                }
            }
        }
    };
    private QufuPeopleCardSaleRequsetBean cardSaleRequsetBean;
    private QufufTerminalTypeListRequestBean terminalTypeListRequestBean;
    private List<QufufTerminalTypeListResultBean.DataBean> terminalList;
    private Thread thread;
    private boolean threadStop;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    protected int getView() {
        return R.layout.activity_qufu_ka_home;
    }

    @Override
    public void init() {

        mContext = this;
        // 修改密码对象
        if (userPassWordRequsetBean == null) {
            userPassWordRequsetBean = new QufuUpdateUserPassWordRequsetBean();
        }

        if (cardSaleRequsetBean == null) {
            cardSaleRequsetBean = new QufuPeopleCardSaleRequsetBean();
        }

        if (terminalTypeListRequestBean == null) {
            terminalTypeListRequestBean = new QufufTerminalTypeListRequestBean();
        }

        if (terminalList == null) {
            terminalList = new ArrayList<>();
        }

        if (bindRequsetBean == null) {
            bindRequsetBean = new QufuAddOrRelieveTerminalBindRequsetBean();
        }

        setting = findViewById(R.id.rl_home_setting);
        makeKa = findViewById(R.id.ll_home_make_ka);
        searchKa = findViewById(R.id.ll_home_search);
        changePw = findViewById(R.id.tv_home_change_pw);

        IntentFilter filter = new IntentFilter();
        filter.addAction(ACTION_USB_PERMISSION);
        filter.addAction(UsbManager.ACTION_USB_ACCESSORY_ATTACHED);
        mContext.registerReceiver(mUsbReceiver, filter);
        //开启身份证读卡器
        if (bopen) {
            return;
        }
        RequestDevicePermission();

        doThing();

        // 启动服务， 去更新 token
        startService(new Intent(QufuKaHomeActivity.this, RefreshTokenService.class));

    }

    private void doThing() {

        setting.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //绑定 就先去查询可以绑定的列表
                findTerminalTypeList();
            }
        });

        // 市民卡办理页面
        makeKa.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String meationName = (String) SPUtils.get(QufuKaHomeActivity.this, Customer.QUFU_TERMINALNAME, "");
                if (StringUtil.isNullOrEmpty(meationName)) {
                    SelfToastUtil.getInstance().show("请先点击右上角设置进行绑定操作");
                    return;
                }
                isShowMakeKa = true;
                isShowSearKa = false;
                if (dialog != null) {
                    dialog.dismiss();
                    dialog = null;
                }
                if (dialog == null) {
                    dialog = new BottomDialog(QufuKaHomeActivity.this, "", "", "");
                }
                dialog.show();
                dialog.setComfirmListener(new BottomDialog.ComfirmListener() {
                    @Override
                    public void comfirm(String name, String sex, String id, String phone) {
                        if (StringUtil.isNullOrEmpty(name)) {
                            SelfToastUtil.getInstance().show("持卡人姓名为空，请确认");
                            return;
                        }
                        if (StringUtil.isNullOrEmpty(sex)) {
                            SelfToastUtil.getInstance().show("性别为空，请确认");
                            return;
                        }
                        if (StringUtil.isNullOrEmpty(id)) {
                            SelfToastUtil.getInstance().show("证件号码为空，请确认");
                            return;
                        }
                        if (StringUtil.isNullOrEmpty(phone)) {
                            SelfToastUtil.getInstance().show("手机号码为空，请确认");
                            return;
                        }

                        // 如果都不为空，那么就去办卡
                        if (sex.equals("男")) {
                            peopleCardSale(name, "0", id, phone);
                        } else {
                            peopleCardSale(name, "1", id, phone);
                        }

                    }
                });
            }
        });

        searchKa.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String meationName = (String) SPUtils.get(QufuKaHomeActivity.this, Customer.QUFU_TERMINALNAME, "");
                if (StringUtil.isNullOrEmpty(meationName)) {
                    SelfToastUtil.getInstance().show("请先点击右上角设置进行绑定操作");
                    return;
                }
                isShowMakeKa = false;
                isShowSearKa = true;
                if (searDialog != null) {
                    searDialog.dismiss();
                    searDialog = null;
                }

                if (searDialog == null) {
                    searDialog = new SearKaDialog(QufuKaHomeActivity.this, "", "", BASE_URL, headers);
                }
                searDialog.show();
            }
        });

        changePw.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                gotoChangePw();
            }
        });
    }

    // 查询可绑定终端列表
    private void findTerminalTypeList() {
        terminalTypeListRequestBean.setTerminalTypeStr("7");
        RetrofitClient.getInstance(QufuKaHomeActivity.this, BASE_URL, headers).findTerminalNameAndIdByTerminalTypeList(terminalTypeListRequestBean, new BaseSubscriber<QufufTerminalTypeListResultBean>(QufuKaHomeActivity.this) {
            @Override
            public void onError(ExceptionHandle.ResponeThrowable e) {
                SelfToastUtil.getInstance().show(e.message);
            }

            @Override
            public void onNext(QufufTerminalTypeListResultBean qufufTerminalTypeListResultBean) {
                String code = qufufTerminalTypeListResultBean.getCode();
                if (code.equals("200")) {
                    terminalList.clear();
                    if (qufufTerminalTypeListResultBean.getData() != null) {
                        terminalList.addAll(qufufTerminalTypeListResultBean.getData());
                        //数据请求完成，然后再去显示dialog
                        // 终端绑定  bindDialog
                        if (bindDialog == null) {
                            bindDialog = new SettingBindDialog(QufuKaHomeActivity.this, terminalList);
                        }
                        bindDialog.show();

                        bindDialog.setComfirmListener(new SettingBindDialog.ComfirmListener() {
                            @Override
                            public void comfirm(QufufTerminalTypeListResultBean.DataBean number) {
                                //把传递过来的数据，然后去完成绑定
                                gotoBind(number, "0");

                            }
                        });

                        bindDialog.setQuxiaoListener(new SettingBindDialog.QuxiaoListener() {
                            @Override
                            public void Quxiao() {
                                gotoBind(new QufufTerminalTypeListResultBean.DataBean(), "1");
                            }
                        });
                    } else {
                        SelfToastUtil.getInstance().show("查询到的绑定列表为空，请先确认信息");
                    }


                } else {
                    SelfToastUtil.getInstance().show(qufufTerminalTypeListResultBean.getMessage());
                }
            }
        });
    }

    //绑定操作
    private void gotoBind(final QufufTerminalTypeListResultBean.DataBean number, final String i) {
        if (i.equals("0")) {
            bindRequsetBean.setTerminalId(number.getTerminalId() + "");
        } else {
            bindRequsetBean.setTerminalId((String) SPUtils.get(QufuKaHomeActivity.this, Customer.QUFU_TERMINALID, ""));
        }

        bindRequsetBean.setTerminalSetFlag(i);
        bindRequsetBean.setTerminalComputerCpuId((String) SPUtils.get(QufuKaHomeActivity.this, Customer.QUFU_DEVICE_ID, "") + "");
        bindRequsetBean.setTerminalComputerName("立式人脸采集");

        RetrofitClient.getInstance(QufuKaHomeActivity.this, BASE_URL, headers).addOrRelieveTerminalBind(bindRequsetBean, new BaseSubscriber<QufuAddOrRelieveTerminalBindResultBean>(QufuKaHomeActivity.this) {
            @Override
            public void onError(ExceptionHandle.ResponeThrowable e) {
                SelfToastUtil.getInstance().show(e.message);
            }

            @Override
            public void onNext(QufuAddOrRelieveTerminalBindResultBean qufuAddOrRelieveTerminalBindResultBean) {
                String code = qufuAddOrRelieveTerminalBindResultBean.getCode();
                if (code.equals("200")) {
                    SelfToastUtil.getInstance().show(qufuAddOrRelieveTerminalBindResultBean.getMessage());
                    if (i.equals("0")) {
                        //如果类型是0 ，就保存
                        SelfToastUtil.getInstance().show("绑定成功");
                        SPUtils.put(QufuKaHomeActivity.this, Customer.QUFU_TERMINALID, number.getTerminalId() + "");
                        SPUtils.put(QufuKaHomeActivity.this, Customer.QUFU_TERMINALNAME, number.getTerminalShortName());
                    } else {
                        SPUtils.put(QufuKaHomeActivity.this, Customer.QUFU_TERMINALID, "");
                        SPUtils.put(QufuKaHomeActivity.this, Customer.QUFU_TERMINALNAME, "");
                        SelfToastUtil.getInstance().show("取消绑定成功");
                    }
                    if (bindDialog != null) {
                        bindDialog.dismiss();
                        bindDialog = null;
                    }
                } else {
                    SelfToastUtil.getInstance().show(qufuAddOrRelieveTerminalBindResultBean.getMessage());
                }
            }
        });

    }

    // 发卡流程，去发卡
    private void peopleCardSale(String name, String sex, String id, String phone) {

        cardSaleRequsetBean.setBuyerName(name);
        cardSaleRequsetBean.setGender(sex);
        cardSaleRequsetBean.setCertificateNo(id);
        cardSaleRequsetBean.setPhoneNumber(phone);
        RetrofitClient.getInstance(QufuKaHomeActivity.this, BASE_URL, headers).peopleCardSale(cardSaleRequsetBean, new BaseSubscriber<QufuPeopleCardSaleResultBean>(QufuKaHomeActivity.this) {
            @Override
            public void onError(ExceptionHandle.ResponeThrowable e) {

                SelfToastUtil.getInstance().show(e.message);
            }

            @Override
            public void onNext(QufuPeopleCardSaleResultBean qufuPeopleCardSaleResultBean) {

                String code = qufuPeopleCardSaleResultBean.getCode();
                if (code.equals("200")) {
                    SelfToastUtil.getInstance().show(qufuPeopleCardSaleResultBean.getMessage());
                    dialog.dismiss();
                } else {
                    SelfToastUtil.getInstance().show(qufuPeopleCardSaleResultBean.getMessage());
                }
            }
        });

    }

    private void gotoChangePw() {
        changePwWindow = new CustomChangePwWindow(QufuKaHomeActivity.this);

        changePwWindow.showAtLocation(changePw, Gravity.BOTTOM | Gravity.CENTER_VERTICAL, 0, 0);
        changePwWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                changePwWindow.backgroundAlpha(QufuKaHomeActivity.this, 1f);
            }
        });

        changePwWindow.setquerenListener(new CustomChangePwWindow.QuerenListener() {
            @Override
            public void querenClick(String yuan, String xin, String que) {
                // 点击确认，后的操作
                String pw = (String) SPUtils.get(QufuKaHomeActivity.this, Customer.QUFU_LOGIN_PASSWORD, "");
                if (!yuan.equals(pw)) {
                    SelfToastUtil.getInstance().show("您输入的原密码，和账户密码不一致，请重新输入");
                    return;
                }
                if (!xin.equals(que)) {
                    SelfToastUtil.getInstance().show("您输入的新密码，和确认密码不一致，请重新输入");
                    return;
                }
                if (xin.equals(yuan)) {
                    SelfToastUtil.getInstance().show("您输入的新密码，和原密码相同，请重新输入");
                    return;
                }

                // 密码校验完毕，可以发起请求进行 更改密码
                GotoChangePw(yuan, xin);

            }
        });
    }

    private void GotoChangePw(String yuan, final String xin) {
        userPassWordRequsetBean.setPassword(yuan);
        userPassWordRequsetBean.setNewPassword(xin);
        RetrofitClient.getInstance(QufuKaHomeActivity.this, BASE_URL, headers).updateUserPassWord(userPassWordRequsetBean, new BaseSubscriber<QufuUpdateUserPassWordResultBean>(QufuKaHomeActivity.this) {
            @Override
            public void onError(ExceptionHandle.ResponeThrowable e) {
                SelfToastUtil.getInstance().show(e.message);
            }

            @Override
            public void onNext(QufuUpdateUserPassWordResultBean qufuUpdateUserPassWordResultBean) {
                String code = qufuUpdateUserPassWordResultBean.getCode();
                if (code.equals("200")) {
                    SPUtils.put(QufuKaHomeActivity.this, Customer.QUFU_LOGIN_PASSWORD, xin);
                    SelfToastUtil.getInstance().show(qufuUpdateUserPassWordResultBean.getMessage());

                    //由于修改密码所以要跳出去
                    startActivity(new Intent(QufuKaHomeActivity.this, LoginActivity.class));
                    SPUtils.put(QufuKaHomeActivity.this, Customer.QUFU_LOGIN_PASSWORD, "");
                    SPUtils.put(QufuKaHomeActivity.this, Customer.QUFU_IS_REMBER, false);
                    finish();
                } else {
                    SelfToastUtil.getInstance().show(qufuUpdateUserPassWordResultBean.getMessage());
                }
            }
        });
    }

    public void OpenDevice() {
        if (bopen) {
            SelfToastUtil.getInstance().show("设备已连接");
            return;
        }
        try {
            startIDCardReader();
            IDCardReaderExceptionListener listener = new IDCardReaderExceptionListener() {
                @Override
                public void OnException() {
                    //出现异常，关闭设备
                    CloseDevice();
                    //当前线程为工作线程，若需操作界面，请在UI线程处理
                    runOnUiThread(new Runnable() {
                        public void run() {
                            SelfToastUtil.getInstance().show("设备发生异常，断开连接！");
                        }
                    });
                }
            };
            idCardReader.open(0);
            idCardReader.setIdCardReaderExceptionListener(listener);
            bStoped = false;
            mReadCount = 0;
            writeLogToFile("连接设备成功");
            SelfToastUtil.getInstance().show("连接成功");
            bopen = true;
            countdownLatch = new CountDownLatch(1);
            thread = new Thread(new Runnable() {
                public void run() {
                    while (!bStoped) {
                        try {
                            Thread.sleep(500);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }

                        boolean ret = false;
                        final long nTickstart = System.currentTimeMillis();
                        try {
                            if (idCardReader != null) {
                                idCardReader.findCard(0);
                                idCardReader.selectCard(0);
                            }
                        } catch (IDCardReaderException e) {
                            //continue;
                        }
                        try {
                            Thread.sleep(50);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        int retType = 0;
                        try {
                            retType = idCardReader.readCardEx(0, 0);
                        } catch (IDCardReaderException e) {
                            writeLogToFile("读卡失败，错误信息：" + e.getMessage());
                        }
                        if (retType == 1 || retType == 2 || retType == 3) {
                            final long nTickUsed = (System.currentTimeMillis() - nTickstart);
                            final int final_retType = retType;
                            writeLogToFile("读卡成功：" + (++mReadCount) + "次" + "，耗时：" + nTickUsed + "毫秒");
                            runOnUiThread(new Runnable() {
                                public void run() {
                                    if (final_retType == 1) {
                                        LogUtil.d(TimeUtil.getLocationTime());
                                        final IDCardInfo idCardInfo = idCardReader.getLastIDCardInfo();
                                        //姓名adb
                                        final String strName = idCardInfo.getName();
                                        //民族
                                        String strNation = idCardInfo.getNation();
                                        //出生日期
                                        String strBorn = idCardInfo.getBirth();
                                        //住址
                                        String strAddr = idCardInfo.getAddress();
                                        //身份证号
                                        final String strID = idCardInfo.getId();
                                        //有效期限
                                        String strEffext = idCardInfo.getValidityTime();

                                        final String Sex = idCardInfo.getSex();


                                        runOnUiThread(new Runnable() {
                                            @Override
                                            public void run() {
                                                // 只有点击按钮 点击了 才去显示
                                                LogUtil.d("isShowMakeKa:" + isShowMakeKa + "-----" + "isShowSearKa:" + isShowSearKa + TimeUtil.getLocationTime());
                                                if (isShowMakeKa) {
                                                    timeNew = TimeUtil.getLocationTimeLong();
                                                    if (!checkIDAgain(strID)) {
                                                        if (dialog != null) {
                                                            LogUtil.d("dialog 不为空，要去清除");
                                                            dialog.dismiss();
                                                            dialog = null;
                                                        }
                                                        if (dialog == null) {
                                                            LogUtil.d("dialog 为空，要去新建");
                                                            dialog = new BottomDialog(QufuKaHomeActivity.this, strName, Sex, strID);
                                                        }
                                                        dialog.show();

                                                        dialog.setComfirmListener(new BottomDialog.ComfirmListener() {
                                                            @Override
                                                            public void comfirm(String name, String sex, String id, String phone) {

                                                                if (StringUtil.isNullOrEmpty(name)) {
                                                                    SelfToastUtil.getInstance().show("持卡人姓名为空，请确认");
                                                                    return;
                                                                }
                                                                if (StringUtil.isNullOrEmpty(sex)) {
                                                                    SelfToastUtil.getInstance().show("性别为空，请确认");
                                                                    return;
                                                                }
                                                                if (StringUtil.isNullOrEmpty(id)) {
                                                                    SelfToastUtil.getInstance().show("证件号码为空，请确认");
                                                                    return;
                                                                }
                                                                if (StringUtil.isNullOrEmpty(phone)) {
                                                                    SelfToastUtil.getInstance().show("手机号码为空，请确认");
                                                                    return;
                                                                }

                                                                // 如果都不为空，那么就去办卡
                                                                if (sex.equals("男")) {
                                                                    peopleCardSale(name, "0", id, phone);
                                                                } else {
                                                                    peopleCardSale(name, "1", id, phone);
                                                                }

                                                            }
                                                        });
                                                    }

                                                }

                                                if (isShowSearKa) {
                                                    timeNew = TimeUtil.getLocationTimeLong();
                                                    if (!checkIDAgain(strID)) {
                                                        if (searDialog != null) {
                                                            searDialog.dismiss();
                                                            searDialog = null;
                                                        }
                                                        if (searDialog == null) {
                                                            searDialog = new SearKaDialog(QufuKaHomeActivity.this, strName, strID, BASE_URL, headers);
                                                        }
                                                        searDialog.show();
                                                    }
                                                }
                                            }
                                        });

                                    } else if (final_retType == 2) {
                                        LogUtil.d(TimeUtil.getLocationTime());
                                        final IDPRPCardInfo idprpCardInfo = idCardReader.getLastPRPIDCardInfo();
                                        //中文名
                                        String strCnName = idprpCardInfo.getCnName();
                                        //英文名
                                        String strEnName = idprpCardInfo.getEnName();
                                        //国家/国家地区代码
                                        String strCountry = idprpCardInfo.getCountry() + "/" + idprpCardInfo.getCountryCode();//国家/国家地区代码
                                        //出生日期
                                        String strBorn = idprpCardInfo.getBirth();
                                        //身份证号
                                        String strID = idprpCardInfo.getId();
                                        //有效期限
                                        String strEffext = idprpCardInfo.getValidityTime();


                                    } else {
                                        LogUtil.d(TimeUtil.getLocationTime());
                                        final IDCardInfo idCardInfo = idCardReader.getLastIDCardInfo();
                                        //姓名
                                        String strName = idCardInfo.getName();
                                        //民族,港澳台不支持该项
                                        String strNation = "";
                                        //出生日期
                                        String strBorn = idCardInfo.getBirth();
                                        //住址
                                        String strAddr = idCardInfo.getAddress();
                                        //身份证号
                                        String strID = idCardInfo.getId();
                                        //有效期限
                                        String strEffext = idCardInfo.getValidityTime();
                                        //签发机关
                                        String strIssueAt = idCardInfo.getDepart();
                                        //通行证号
                                        String strPassNum = idCardInfo.getPassNum();
                                        //签证次数
                                        int visaTimes = idCardInfo.getVisaTimes();


                                    }
                                }
                            });
                        }
                    }
                    countdownLatch.countDown();
                }
            });
            thread.start();
        } catch (IDCardReaderException e) {
            SelfToastUtil.getInstance().show("连接设备失败");
        }
    }

    // 返回 true  相同 小于  10 秒  那么就 不处理
    private boolean checkIDAgain(String m_strIDCards) {
        if (m_strIDCards.equals(OldID) && timeNew - timeOld < 1000 * 0.1) {
//            SelfToastUtil.getInstance().show("同一张身份证，1秒内不可重复操作");
            System.out.println("zyf  未超过10秒 拒绝访问" + TimeUtil.getLocationTime());
            return true;
        } else {
            System.out.println("zyf  超过10秒 去访问" + TimeUtil.getLocationTime());
            timeOld = timeNew;
            OldID = m_strIDCards;
            return false;
        }
    }


    private void startIDCardReader() {
        if (null != idCardReader) {
            IDCardReaderFactory.destroy(idCardReader);
            idCardReader = null;
        }
        // Define output log level
        LogHelper.setLevel(Log.VERBOSE);
        // Start fingerprint sensor
        Map idrparams = new HashMap();
        idrparams.put(ParameterHelper.PARAM_KEY_VID, VID);
        idrparams.put(ParameterHelper.PARAM_KEY_PID, PID);
        idCardReader = IDCardReaderFactory.createIDCardReader(this, TransportType.USB, idrparams);
    }

    public static void writeLogToFile(String log) {
        try {
            File dirFile = new File("/sdcard/zkteco/");  //目录转化成文件夹
            if (!dirFile.exists()) {              //如果不存在，那就建立这个文件夹
                dirFile.mkdirs();
            }
            String path = "/sdcard/zkteco/idrlog.txt";
            File file = new File(path);
            if (!file.exists()) {
                File dir = new File(file.getParent());
                dir.mkdirs();
                file.createNewFile();
            }
            FileOutputStream outStream = new FileOutputStream(file, true);
            log += "\r\n";
            outStream.write(log.getBytes());
            outStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void CloseDevice() {
        if (!bopen) {
            return;
        }
        bStoped = true;
        mReadCount = 0;
        if (null != countdownLatch) {
            try {
                countdownLatch.await(10, TimeUnit.SECONDS);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        try {
            idCardReader.close(0);
        } catch (IDCardReaderException e) {
            e.printStackTrace();
        }
        bopen = false;
    }

    private void RequestDevicePermission() {
        musbManager = (UsbManager) this.getSystemService(Context.USB_SERVICE);

        for (UsbDevice device : musbManager.getDeviceList().values()) {
            if (device.getVendorId() == VID && device.getProductId() == PID) {
                Intent intent = new Intent(ACTION_USB_PERMISSION);
                PendingIntent pendingIntent = PendingIntent.getBroadcast(mContext, 0, intent, 0);
                musbManager.requestPermission(device, pendingIntent);
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (thread != null) {
            bStoped = true;
            thread.interrupt();
        }

        IDCardReaderFactory.destroy(idCardReader);
        mContext.unregisterReceiver(mUsbReceiver);
    }

}
